//
//  AFYFileManage.m
//  NewsTestDemo
//
//  Created by yzrs on 16/11/28.
//  Copyright © 2016年 方媛. All rights reserved.
//

#import "AFYFileManage.h"
#import "NSString+DIY.h"

@implementation AFYFileManage

+(instancetype)shareAfyFileManager{
    static AFYFileManage *afyManage = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        afyManage = [[AFYFileManage alloc] init];
    });
    return afyManage;
}

//保存图片
-(BOOL)saveImageData:(NSData *)imageData forKey:(NSString *)fileName toPath:(NSString *)path{
    if (!path) {
        return NO;
    }
    NSString *filePath = [path stringByAppendingPathComponent:fileName.hashString];
    return [imageData writeToFile:filePath atomically:YES];
    
    return NO;
}

//获取目录所有文件名
-(NSArray *)getImageNameArrayByPath:(NSString *)path{
    if (!path) {
        return nil;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *nameArray = [fileManager contentsOfDirectoryAtPath:path error:nil];
    return nameArray;
}

//返回数据@{key:data}
-(NSDictionary *)isFileExistByTheKey:(NSString *)key toPath:(NSString *)path{
    NSArray *fileNameArray = [self getImageNameArrayByPath:path];
    NSString *hashString = key.hashString;
    for (NSString *keyTemp in fileNameArray) {
        if ([hashString isEqualToString:keyTemp]) {
            NSString *pathTemp = [path stringByAppendingPathComponent:hashString];
            NSData   *data = [NSData dataWithContentsOfFile:pathTemp];
            if (data) {
                return @{key:data};
            }
            break;
        }
    }
    return nil;
}

/* 1.0 缓存数据 缓存数据 缓存数据 */

//懒加载 缓存数据目录
-(NSString *)afyCachePath{
    if (!_afyCachePath) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/ImageCache"];
        BOOL isDir = NO;
        BOOL isExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
        
        if (isDir && isExist) {
            _afyCachePath = path;
        }else{
            BOOL createFlag = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            if (createFlag) {
                _afyCachePath = path;
            }
        }
    }
    return _afyCachePath;
}

//1.1
-(BOOL)saveCacheImageWithData:(NSData *)data forKey:(NSString *)key
{
    if ([key isKindOfClass:[NSString class]] && [data isKindOfClass:[NSData class]]) {
        //参数符合  则进行保存操作
        return [self saveImageData:data forKey:key toPath:self.afyCachePath];
    }else{
        return NO;//参数类型不符
    }
}
//1.2 清除缓存
-(BOOL)clearCacheImageData{
    if (!self.afyCachePath) {
        return nil;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager removeItemAtPath:self.afyCachePath error:nil];
    if (result) {
        self.afyCachePath = nil;
    }
    return result;
}
//1.3 返回缓存数据
-(NSDictionary *)isCacheFileExistByTheKey:(NSString *)key{
    if (![key isKindOfClass:[NSString class]]) {
        return nil;
    }
    return [self isFileExistByTheKey:key toPath:self.afyCachePath];
}

/* 2.0 收藏 收藏 收藏 */

-(NSString *)afyCollectPath{
    if (!_afyCollectPath) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/ImageCollect"];
        BOOL isDir = NO;
        BOOL isExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
        
        if (isDir && isExist) {
            _afyCollectPath = path;
        }else{
            BOOL createFlag = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            if (createFlag) {
                _afyCollectPath = path;
            }
        }
    }
    return _afyCollectPath;
}

-(NSString *)afyCollectDict{
    if (!_afyCollectDict) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/ImageCollectDict"];
        BOOL isDir = NO;
        BOOL isExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
        
        if (isDir && isExist) {
            _afyCollectDict = [path stringByAppendingPathComponent:@"order.order"];
        }else{
            BOOL createFlag = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            if (createFlag) {
                _afyCollectDict = [path stringByAppendingPathComponent:@"order.order"];
            }
        }
    }
    return _afyCollectDict;
}

//2.1 添加收藏
-(BOOL)addToCollectDirWithData:(NSData *)data forKey:(NSString *)key
{
    if ([key isKindOfClass:[NSString class]] && [data isKindOfClass:[NSData class]]) {
        //参数符合  则进行保存操作
        if ([self saveImageData:data forKey:key toPath:self.afyCollectPath])
        {
            if ([self savedCollectOrderWithPath:key])
            {
                return YES;
            }
        }
    }else{
        return NO;//参数类型不符
    }
    
    return NO;
}

-(BOOL)savedCollectOrderWithPath:(NSString *)key{
    if (!self.afyCollectDict) {
        return NO;
    }
    NSMutableArray *collectArray = [NSMutableArray arrayWithArray:[self getCollectArray]];
    [collectArray addObject:key];
    
    return [NSKeyedArchiver archiveRootObject:collectArray toFile:self.afyCollectDict];
}

-(NSArray *)getCollectArray{
    if (!self.afyCollectDict) {
        return nil;
    }
    NSArray *collectArray = [NSKeyedUnarchiver unarchiveObjectWithFile:self.afyCollectDict];
    if ([collectArray isKindOfClass:[NSArray class]]) {
        return collectArray;
    }
    return nil;
}

//2.2 返回收藏 数据
-(NSArray *)getTheCollectionData{
    NSArray *fileNameArray = [self getCollectArray];
    NSMutableArray *resultArray = [NSMutableArray array];
    if (fileNameArray) {
        for (NSString *key in fileNameArray) {
            NSString *path = [self.afyCollectPath stringByAppendingPathComponent:key.hashString];
            NSData *data = [NSData dataWithContentsOfFile:path];
            if (data) {
                [resultArray addObject:@{key:data}];
            }
        }
        return resultArray;
    }
    
    return nil;
}

//删除收藏数据
-(BOOL)deletCollectDataByTheKey:(NSString *)key{
    if (!key || ![key isKindOfClass:[NSString class]]) {
        return NO;
    }
    NSMutableArray *collectArray = [NSMutableArray arrayWithArray:[self getCollectArray]];
    if (collectArray.count) {
        for (int i=0; i<collectArray.count; i++) {
            NSString *collectString = [collectArray objectAtIndex:i];
            if ([collectString isEqualToString:key]) {
                [collectArray removeObjectAtIndex:i];
                
                [self deleFileByThePath:[self.afyCollectPath stringByAppendingPathComponent:key.hashString]];
                
                return [NSKeyedArchiver archiveRootObject:collectArray toFile:self.afyCollectDict];
            }
        }
    }
    
    return NO;
}



-(BOOL)deleFileByThePath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager removeItemAtPath:path error:nil];
}

@end
